package com.lottery.material.controller.portal.user;

import com.lottery.material.controller.base.BaseController;
import com.lottery.material.enumeration.ResultEnum;
import com.lottery.material.jedis.JedisClient;
import com.lottery.material.pojo.circle.CircleInfo;
import com.lottery.material.pojo.circle.CircleMemberInfo;
import com.lottery.material.pojo.portaluser.FollowInfo;
import com.lottery.material.pojo.portaluser.PortalUserInfo;
import com.lottery.material.resolver.CustomException;
import com.lottery.material.service.portal.circle.CircleInfoService;
import com.lottery.material.service.portal.circle.CircleMemberInfoService;
import com.lottery.material.service.portal.user.FollowInfoService;
import com.lottery.material.service.portal.user.PortalUserInfoService;
import com.lottery.material.util.*;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * Description:    关注Controller
 * Author:         sunny
 * CreateDate:     2019-04-15 10:59
 */
@RequestMapping("/portal/user")
@Slf4j
@Controller
public class PortalUserFollowController extends BaseController {

    @Autowired
    @Qualifier("jedisClientCluster")
    private JedisClient jedisClient;

    @Autowired
    private FollowInfoService followInfoService;
    @Autowired
    private CircleMemberInfoService circleMemberInfoService;
    @Autowired
    private PortalUserInfoService portalUserInfoService;
    @Autowired
    private CircleInfoService circleInfoService;

    private Map<String, String> reqParamMap = new HashMap<String, String>();
    /**
     * description: 关注用户或圈子
     * author sunny
     * createDate 2019-04-15 上午 11:03
     * @param request
     * @return
     */
    @RequestMapping(value = "/goFollow", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult goFollow(HttpServletRequest request) {
        Map<String, String> reqParamMap = new HashMap<>();
        //解析参数
        if (ParameterUtil.analyticParameter(request, reqParamMap)) {
            throw new CustomException(ResultEnum.PARSE_EXCEPTION);
        }

        //非空判断及用户登录是否过期验证
        ParameterUtil.checkLogin(reqParamMap, jedisClient, portalUserInfoService);

        ResponseResult respDate = validateEmpty(reqParamMap);
        if (null != respDate) {
            return respDate;
        }

        String isFollow = reqParamMap.get("isFollow");  //1：取消关注；2：关注
        if (StringUtils.isBlank(isFollow)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "isFollow");
        } else if (!"1".equals(isFollow) && !"2".equals(isFollow)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_ERROR, "isFollow");
        }
        String followType = reqParamMap.get("followType");  //1：用户；2：圈子
        if (StringUtils.isBlank(followType)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "followType");
        } else if (!"1".equals(followType) && !"2".equals(followType)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_ERROR, "followType");
        }
        String objectId = reqParamMap.get("objectId");
        if (StringUtils.isBlank(objectId)) {
            return ResponseResult.buildFormatResult(ResultEnum.PARAMETER_NOT_NULL, "objectId");
        }

        //签名验证
        ResponseResult responseResult = ParameterUtil.checkSign(reqParamMap);
        if (null != responseResult) {
            return responseResult;
        }

        try {
            //封装数据
            if ("1".equals(followType)) { //关注用户
                PortalUserInfo portalUserInfo = portalUserInfoService.findByUserId(objectId);
                if(Objects.isNull(portalUserInfo)){
                    return ResponseResult.buildResult(ResultEnum.USER_NOT_EXIST_FAIL);
                }

                FollowInfo userFollowInfo = new FollowInfo();
                userFollowInfo.setUserId(reqParamMap.get("userId"));
                userFollowInfo.setFollowUserId(objectId);
                if ("1".equals(isFollow)) { //取消关注
                    Integer fansTotal = followInfoService.deleteUserFollow(userFollowInfo);
                    return ResponseResult.buildResult(ResultEnum.NO_FOLLOW_SUCCESS, MathUtil.formatNum(fansTotal.toString(), false));
                } else { //关注
                    userFollowInfo.setCreateTime(CalendarUtil.getSystemCurrentDate());
                    Integer fansTotal = followInfoService.saveUserFollow(userFollowInfo);
                    return ResponseResult.buildResult(ResultEnum.FOLLOW_SUCCESS, MathUtil.formatNum(fansTotal.toString(), false));
                }
            } else {  //关注圈子
                CircleInfo circleInfo = circleInfoService.findByCircleId(objectId);
                if(Objects.isNull(circleInfo)){
                    return ResponseResult.buildResult(ResultEnum.CIRCLE_NOT_EXIST_FAIL);
                }

                CircleMemberInfo circleMemberInfo = new CircleMemberInfo();
                circleMemberInfo.setUserId(reqParamMap.get("userId"));
                circleMemberInfo.setCircleId(Integer.valueOf(objectId));
                if ("1".equals(isFollow)) { //取消关注
                    Integer fansTotal = circleMemberInfoService.deleteCircleMember(circleMemberInfo, circleInfo);
                    return ResponseResult.buildResult(ResultEnum.NO_FOLLOW_SUCCESS, MathUtil.formatNum(fansTotal.toString(), false));
                } else {    //关注
                    circleMemberInfo.setCreateTime(CalendarUtil.getSystemCurrentDate());
                    circleMemberInfo.setRank(1);
                    circleMemberInfo.setIsBan(1);
                    circleMemberInfo.setIsTop(1);
                    Integer fansTotal = circleMemberInfoService.saveCircleMember(circleMemberInfo, circleInfo);
                    return ResponseResult.buildResult(ResultEnum.FOLLOW_SUCCESS, MathUtil.formatNum(fansTotal.toString(), false));
                }
            }
        } catch (Exception e) {
            log.error("【关注用户或圈子出现异常】:{}", ExceptionUtil.logExceptionStack(e));
            if ("1".equals(isFollow)) {
                throw new CustomException(ResultEnum.NO_FOLLOW_FAIL);
            } else {
                throw new CustomException(ResultEnum.FOLLOW_FAIL);
            }
        }
    }


    /**
     * @Author 肖拔赟
     * @Description 6.1	获取关注的达人列表接口
     * @Date Created on 2019-04-25 9:43
     * @param  request
     * @return ResponseResult
     */
    @ApiOperation(value = "获取关注的达人列表接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "userId", required = true),
            @ApiImplicitParam(name = "page", value = "分页", required = true)
    })
    @RequestMapping(value = "/getFollowList", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult getFollowList(HttpServletRequest request) {
        //System.err.println("reqParamMap-->" + reqParamMap.toString());
        //验证请求参数（非空，签名）
        ResponseResult validate = super.validate(request, reqParamMap);
        if(null != validate){
            return validate;
        }

        //userId非空判断及用户登录是否过期验证
        ParameterUtil.checkLogin(reqParamMap, jedisClient, portalUserInfoService);

        if(!StringUtils.isNumeric(reqParamMap.get("page"))){
            return ResponseResult.buildResult(400, "分页参数page必须为数字");
        }

        try{
            return ResponseResult.buildSuccess(
                    followInfoService.getFollowListListPage(reqParamMap.get("userId"), Integer.valueOf(reqParamMap.get("page"))));
        }catch (Exception e){
            log.error("获取关注的达人列表接口异常-》{}", ExceptionUtil.logExceptionStack(e));
            throw new CustomException(ResultEnum.GET_FOLLOW_INFO_LIST_EXCEPTION);
        }

    }

    /**
     * @Author 肖拔赟
     * @Description 6.2获取达人排行榜接口
     * @Date Created on 2019-04-26 9:33
     * @param request
     * @return
     */
    @ApiOperation(value = "6.2获取达人排行榜接口")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "userId", value = "userId", required = true),
            @ApiImplicitParam(name = "page", value = "分页", required = true)
    })
    @RequestMapping(value = "/getFollowRanking", method = RequestMethod.POST)
    @ResponseBody
    public ResponseResult getFollowRanking(HttpServletRequest request) {
        //验证请求参数（非空，签名）
        ResponseResult validate = super.validate(request, reqParamMap);
        if(null != validate){
            return validate;
        }

        String page = reqParamMap.get("page");
        if(!StringUtils.isNumeric(page)){
            return ResponseResult.buildResult(400, "分页参数page必须为数字");
        }

        String userId = reqParamMap.get("userId");
        String accessToken = reqParamMap.get("accessToken");
        if (StringUtils.isNotBlank(userId) && StringUtils.isNotBlank(accessToken)) {
            Object hget = jedisClient.hget("portalUser", userId);
            String s = String.valueOf(hget);
            if (!accessToken.equals(s)) {
                return ResponseResult.buildResult(ResultEnum.LOGIN_OUTOFDATE_ERROR);
            }
        }

        try{

            return ResponseResult.buildSuccess(
                    followInfoService.getFollowRankingListPage(userId, Integer.valueOf(page)));

        }catch (Exception e){
            log.error("获取达人排行榜列表出现异常-》{}", ExceptionUtil.logExceptionStack(e));
            throw new CustomException(ResultEnum.GET_FOLLOW_RANKING_LIST_EXCEPTION);
        }

    }
}
